from Manage.db_connector import DBUtils

class DepositManager:
    def __init__(self):
        self.db = DBUtils()
        self.db.connect()

    def __del__(self):
        self.db.disconnect()

    def get_all_deposit_types(self):
        """
        获取所有存款类型（含描述）
        返回:
            list: 存款类型列表，每个元素包含 savingID, savingName 和 descrip
            示例: [{'savingID':1, 'savingName':'活期', 'descrip':'灵活存取'}, ...]
        """
        query = "SELECT savingID, savingName, descrip FROM deposit ORDER BY savingID"
        try:
            result = self.db.execute_query(query)
            return result if result else []
        except Exception as e:
            print(f"获取存款类型失败: {e}")
            return None

    def add_deposit_type(self, saving_name, description=None):
        """
        添加存款类型
        参数:
            saving_name: 存款类型名称(20字符以内)
            description: 存款类型描述(可选)
        返回:
            savingID: 新添加的存款类型ID
        """
        query = """
        INSERT INTO deposit (savingName, descrip)
        VALUES (%s, %s)
        """
        params = (saving_name, description)

        try:
            result = self.db.execute_query(query, params, fetch=False)
            if result:
                # 获取新插入的ID
                new_id = self.db.execute_query("SELECT LAST_INSERT_ID() as id")[0]['id']
                print(f"成功添加存款类型: {saving_name} (ID: {new_id})")
                return new_id
            return None
        except Exception as e:
            print(f"添加存款类型失败: {e}")
            return None

    def update_deposit_type(self, saving_id, saving_name=None, description=None):
        """
        更新存款类型信息
        参数:
            saving_id: 要更新的存款类型ID
            saving_name: 新名称(可选)
            description: 新描述(可选)
        返回:
            bool: 更新是否成功
        """
        updates = []
        params = []

        if saving_name is not None:
            updates.append("savingName = %s")
            params.append(saving_name)

        if description is not None:
            updates.append("descrip = %s")
            params.append(description)

        if not updates:
            print("没有提供更新内容")
            return False

        query = f"UPDATE deposit SET {', '.join(updates)} WHERE savingID = %s"
        params.append(saving_id)

        try:
            result = self.db.execute_query(query, params, fetch=False)
            if result:
                print(f"成功更新存款类型 ID: {saving_id}")
                return True
            print("未找到该存款类型或数据未变更")
            return False
        except Exception as e:
            print(f"更新存款类型失败: {e}")
            return False

    def delete_deposit_type(self, saving_id):
        """
        删除存款类型
        检查是否有银行卡关联该类型
        参数:
            saving_id: 要删除的存款类型ID
        返回:
            bool: 删除是否成功
        """
        # 检查是否有银行卡使用该类型
        check_query = """
        SELECT COUNT(*) as count FROM cardInfo 
        WHERE savingID = %s
        """
        check_result = self.db.execute_query(check_query, (saving_id,))

        if check_result and check_result[0]['count'] > 0:
            print("该存款类型有关联的银行卡，不能删除")
            return False

        query = "DELETE FROM deposit WHERE savingID = %s"
        try:
            result = self.db.execute_query(query, (saving_id,), fetch=False)
            if result:
                print(f"成功删除存款类型 ID: {saving_id}")
                return True
            print("未找到该存款类型")
            return False
        except Exception as e:
            print(f"删除存款类型失败: {e}")
            return False
